//
//  MTWithdrawConfirmController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/24.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import RxSwift
import RxCocoa
import Moya
import Result

class MTWithdrawConfirmController: BaseViewController {
    
    var money: String = "" {
        didSet {
            checkoutMoney.text = "￥\(money)"
        }
    }
    
    var requestParams: [String: Any] = [:]
    
    /// UserApi
    private lazy var user_provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    lazy var bgView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0x2f2f2f)
        return view
    }()
    
    lazy var checkoutLab: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.text = "结算金额"
        label.font = PingFangSCMediumFont(14)
        return label
    }()
    
    lazy var checkoutMoney: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.theme.main
        label.font = PingFangSCSemiboldFont(40)
        label.textAlignment = .right
        return label
    }()
    
    lazy var nextStepButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("下一步", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.clipsToBounds = true
        btn.addTarget(self, action: #selector(withdrawConfirmController(didClickNextButton:)), for: .touchUpInside)
        return btn
    }()

}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MTWithdrawConfirmController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
    }
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MTWithdrawConfirmController {
    
    private func initializeUI() {
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        navigationItem.title = "结算"
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 56, height: 20))
        button.setTitle("联系客服", for: .normal)
        button.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        button.titleLabel?.font = PingFangSCMediumFont(14)
        button.addTarget(self, action: #selector(withdrawConfirmController(didClickContactButton:)), for: .touchUpInside)
        let rightBarButton = UIBarButtonItem(customView: button)
        self.navigationItem.rightBarButtonItem = rightBarButton
        
        view.addSubview(bgView)
        bgView.addSubview(checkoutLab)
        bgView.addSubview(checkoutMoney)
        view.addSubview(nextStepButton)
        
        bgView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(NavigationBarHeight+StatusBarHeight)
            make.height.equalTo(90)
            make.width.equalTo(ScreenWidth)
        }
        
        checkoutLab.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(bgView).offset(10)
        }
        
        checkoutMoney.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalTo(bgView).offset(-10)
        }
        
        
        nextStepButton.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(50)
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 20)
        }
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTWithdrawConfirmController {
    
    private func withdrawConfirmController(didClickContactButton sender: UIButton) {
        if let un = UserCenter.default.customerUserName {
            JMSGConversation.createSingleConversation(withUsername: un) { [weak self] (conversation, error) in
                guard let weakSelf = self else { return }
                if error == nil, conversation != nil {
                    if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[1] as? BaseNavController {
                        nav.selectCategory()
                        
                        DispatchQueue.main.after(0.25) {
                            let conv: JMSGConversation = conversation as! JMSGConversation
                            nav.pushViewController(JCChatViewController(conversation: conv), animated: true)
                        }
                        
                        DispatchQueue.main.after(1, execute: {
                            weakSelf.navigationController?.popToRootViewController(animated: false)
                        })
                    }
                }
            }
        }
    }
    
    private func withdrawConfirmController(didClickNextButton sender: UIButton) {
        let xibView = WithdrawCheckoutAlertView.init(frame: CGRect(x:0, y:0, width:ScreenWidth, height:ScreenHeight))
        xibView.completionHandler = {() -> () in
            self.applyWithdraw()
        }
        UIApplication.shared.keyWindow?.addSubview(xibView)
    }
    
}

extension MTWithdrawConfirmController {
        /// 提现申请
    private func applyWithdraw() {
        user_provider.originRequest(.applyWithdraw(requestParams), callbackQueue: .main, progress: nil) { [weak self] (result, isCache) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let data = try? response.mapJSON() as? [String: Any], let code = data["code"] as? Int {
                    if code == 200 {
                        weakself.navigationController?.pushViewController(MTCheckoutResultController(), animated: true)
                    } else if let msg = data["message"] as? String {
                        AlertManager.presentAlertView(message: msg)
                    } else {
                        AlertManager.presentAlertView(message: "申请失败")
                    }
                } else {
                    AlertManager.presentAlertView(message: "申请失败")
                }
                break
                
            case .failure(_):
                AlertManager.presentAlertView(message: "申请失败")
                break
            }
        }
    }
}

